#!/bin/bash
# 检查是否已经安装了Java
if command -v java &> /dev/null; then
    echo "Java 已经安装"
    exit 0
fi
    echo "Java 未安装，开始安装..."
    # 检查是否已经安装了wget
if ! command -v wget &> /dev/null; then
    echo "wget 为安装"
    apt-get update
    apt-get install -y wget
fi
# 判断java 目录是否存在
if [ -d "$(pwd)/jdk-21.0.5" ]; then
    echo "jdk-21.0.5 目录存在删除"
    rm -rf $(pwd)/jdk-21.0.5
fi
wget -O ./openjdk-21_linux-x64_bin.tar.gz http://192.168.2.252:5244/d/nas/cache/sdk/jdk-21_linux-x64_bin.tar.gz?sign=F1-Muss4U8iTrgsvHcDjD8c4wsMR3UmnZgRE1IIP6Kc=:0
# 下载成功
if [ $? -eq 0 ]; then
    echo "下载成功"
    tar -zxvf openjdk-21_linux-x64_bin.tar.gz
    rm -rf openjdk-21_linux-x64_bin.tar.gz
    echo "安装成功"
else
    echo "下载失败 本地服务器下载"
    wget -O ./openjdk-21_linux-x64_bin.tar.gz https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.tar.gz
    if [ $? -eq 0 ]; then
        echo "下载成功"
        tar -zxvf openjdk-21_linux-x64_bin.tar.gz
        rm -rf openjdk-21_linux-x64_bin.tar.gz
        echo "安装成功"
    else
        echo "下载失败"
    fi

fi

cat >/etc/profile.d/sdk.sh << EOF
#!/bin/bash
#sdk 主目录
export SDK_HOME=$(pwd)
# java 目录
export JAVA_HOME=\$SDK_HOME/jdk-21.0.5
# jar
export JRE_HOME=\$JAVA_HOME/jre
# CLASSPATH
export CLASSPATH=\$JAVA_HOME/lib:\$JRE_HOME/lib:\$CLASSPATH
# java 库
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:\$JAVA_HOME/lib
# gradle 目录
export GRADLE_USER_HOME=\$SDK_HOME/gradle_repo

# PATH
export PATH=\$PATH:\$JAVA_HOME/bin:\$JRE_HOME/bin

EOF

# 刷新环境
source /etc/profile
java -version